import { useState, useEffect } from "react";
import { invoke } from "@tauri-apps/api/core";
import { PasswordForm } from "./PasswordForm";
import { PasswordItem } from "./PasswordItem";

interface EncryptedPassword {
  id: number;
  title: string;
  username?: string;
  encrypted_password: string;
  website?: string;
  notes?: string;
  created_at?: string;
  updated_at?: string;
}

interface DecryptedPassword {
  title: string;
  username?: string;
  password: string;
  website?: string;
  notes?: string;
}

export function PasswordManager() {
  const [passwords, setPasswords] = useState<EncryptedPassword[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState("");
  const [showAddForm, setShowAddForm] = useState(false);
  const [editingPassword, setEditingPassword] = useState<EncryptedPassword | null>(null);
  const [toast, setToast] = useState<{ message: string; type: "success" | "error" | "info" } | null>(null);

  // Load passwords on mount
  useEffect(() => {
    loadPasswords();
  }, []);

  // Auto-hide toast after 3 seconds
  useEffect(() => {
    if (toast) {
      const timer = setTimeout(() => setToast(null), 3000);
      return () => clearTimeout(timer);
    }
  }, [toast]);

  const loadPasswords = async () => {
    try {
      setLoading(true);
      const result = await invoke<EncryptedPassword[]>("get_passwords");
      setPasswords(result);
    } catch (error) {
      console.error("Failed to load passwords:", error);
      showToast("加载密码失败", "error");
    } finally {
      setLoading(false);
    }
  };

  const handleAddPassword = async (decryptedData: DecryptedPassword) => {
    try {
      // Encrypt password data (backend uses cached master password)
      const encryptedData = await invoke<EncryptedPassword>("encrypt_password_data", {
        passwordData: decryptedData,
      });

      // Save to database
      await invoke<number>("save_password", {
        encryptedData,
      });

      showToast("密码添加成功", "success");
      setShowAddForm(false);
      loadPasswords();
    } catch (error) {
      console.error("Failed to add password:", error);
      showToast(`添加密码失败: ${error}`, "error");
    }
  };

  const handleEditPassword = async (decryptedData: DecryptedPassword) => {
    if (!editingPassword) return;

    try {
      // Encrypt updated password data (backend uses cached master password)
      const encryptedData = await invoke<EncryptedPassword>("encrypt_password_data", {
        passwordData: decryptedData,
      });

      // Delete old password
      await invoke("delete_password", { id: editingPassword.id });

      // Save new password (with new encryption)
      await invoke<number>("save_password", {
        encryptedData,
      });

      showToast("密码更新成功", "success");
      setEditingPassword(null);
      loadPasswords();
    } catch (error) {
      console.error("Failed to update password:", error);
      showToast(`更新密码失败: ${error}`, "error");
    }
  };

  const handleDeletePassword = async (id: number) => {
    if (!confirm("确定要删除这个密码吗？")) return;

    try {
      await invoke("delete_password", { id });
      showToast("密码已删除", "success");
      loadPasswords();
    } catch (error) {
      console.error("Failed to delete password:", error);
      showToast(`删除密码失败: ${error}`, "error");
    }
  };

  const handleEditClick = async (password: EncryptedPassword) => {
    setEditingPassword(password);
  };

  const showToast = (message: string, type: "success" | "error" | "info") => {
    setToast({ message, type });
  };

  // Filter passwords based on search query
  const filteredPasswords = passwords.filter(p => {
    const query = searchQuery.toLowerCase();
    return (
      p.title.toLowerCase().includes(query) ||
      (p.username?.toLowerCase().includes(query)) ||
      (p.website?.toLowerCase().includes(query))
    );
  });

  return (
    <div className="h-full flex flex-col bg-background relative">
      {/* Main Content */}
      <div className="flex-1 overflow-hidden flex flex-col">
        {/* Header with Search and Add Button */}
        <div className="p-6 border-b border-border bg-card">
          <div className="flex items-center justify-between mb-4">
            <h1 className="text-2xl font-bold text-foreground">密码管理器</h1>
            <button
              onClick={() => setShowAddForm(true)}
              className="px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90 transition-colors flex items-center gap-2"
            >
              <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
              </svg>
              添加密码
            </button>
          </div>

          {/* Search Bar */}
          <div className="relative">
            <input
              type="text"
              placeholder="搜索标题、用户名或网站..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="w-full px-4 py-2 pl-10 bg-background border border-border rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
            />
            <svg
              className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-muted-foreground"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
            </svg>
          </div>
        </div>

        {/* Password List */}
        <div className="flex-1 overflow-auto">
          {loading ? (
            <div className="text-center py-12">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"></div>
              <p className="text-muted-foreground">加载中...</p>
            </div>
          ) : filteredPasswords.length === 0 ? (
            <div className="text-center py-12">
              <div className="w-16 h-16 bg-muted rounded-full flex items-center justify-center mx-auto mb-4">
                <svg className="w-8 h-8 text-muted-foreground" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
                </svg>
              </div>
              <h3 className="text-lg font-semibold text-foreground mb-2">
                {searchQuery ? "未找到匹配的密码" : "还没有保存任何密码"}
              </h3>
              <p className="text-muted-foreground mb-4">
                {searchQuery ? "尝试使用其他关键词搜索" : '点击上方"添加密码"按钮开始'}
              </p>
            </div>
          ) : (
            <div className="bg-card border-x border-border">
              {/* List Header */}
              <div className="flex items-center gap-3 px-4 py-2 bg-muted/50 border-y border-border text-xs font-medium text-muted-foreground uppercase">
                <div className="flex-1 min-w-[180px]">网站</div>
                <div className="w-[160px]">账户</div>
                <div className="w-[140px]">密码</div>
                <div className="hidden lg:block flex-1 min-w-[120px]">备注</div>
                <div className="w-[220px] text-right">操作</div>
              </div>
              
              {/* List Items */}
              {filteredPasswords.map((password) => (
                <PasswordItem
                  key={password.id}
                  password={password}
                  onEdit={handleEditClick}
                  onDelete={handleDeletePassword}
                  onToast={showToast}
                />
              ))}
            </div>
          )}
        </div>
      </div>

      {/* Add Password Modal */}
      {showAddForm && (
        <PasswordForm
          onSubmit={handleAddPassword}
          onCancel={() => setShowAddForm(false)}
          title="添加新密码"
        />
      )}

      {/* Edit Password Modal */}
      {editingPassword && (
        <PasswordForm
          initialData={editingPassword}
          onSubmit={handleEditPassword}
          onCancel={() => setEditingPassword(null)}
          title="编辑密码"
        />
      )}

      {/* Toast Notification - moved to absolute positioning within container */}
      {toast && (
        <div className={`absolute bottom-4 right-4 px-4 py-3 rounded-lg shadow-lg z-50 flex items-center gap-2 ${
          toast.type === "success" ? "bg-green-500 text-white" :
          toast.type === "error" ? "bg-red-500 text-white" :
          "bg-blue-500 text-white"
        }`}>
          {toast.type === "success" && (
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
            </svg>
          )}
          {toast.type === "error" && (
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
            </svg>
          )}
          <span>{toast.message}</span>
        </div>
      )}
    </div>
  );
}
